﻿using dis.sys.hw1.Service;
using Org.Apache.Zookeeper.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using ZooKeeperNet;
using dis.sys.hw1.Service;

namespace ConsoleApplication1
{
    class Program
    {
        public static ZooKeeper Replicator { get; set; }

        static void Main(string[] args)
        {
            string line = new FileInfo(@"C:\Users\shizr_000\Dropbox\Technion\236351 - Distributed Systems\HW1\dis.sys.hw1\dis.sys.hw1.HotelServiceHost\bin\Debug\zookeeper.conf").OpenText().ReadLine();
            Replicator = new ZooKeeper(line, new TimeSpan(0, 0, 1000), null);

            while (true)
            {
                try
                {
                    Thread.Sleep(5000);
                    //Console.Clear();
                    Console.WriteLine("" + DateTime.Now + "----------------------------");
                    printChildrenRec("/", 0);
                }
                catch 
                {
                }
            }

        }

        private static void printChildrenRec(string node, int depth)
        {
            foreach (var child in Replicator.GetChildren(node,false))
            {
                string mark = new String('-', depth*2);
                String curr = node + (node.EndsWith("/") ? string.Empty : "/") + child;
                Replication.ServerData data = null;
                try {
                data = Replicator.GetData(curr,false,new Stat()).ByteArrayToObject<Replication.ServerData>();
                }catch{}
                Console.WriteLine(mark + child + ":" + data + ((data != null && data.MainHotelName.Equals(child)) ? " - MAIN" : ""));
                printChildrenRec(curr, depth + 1);
            }
        }
    }
}
